package com.asiainfo.iov.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.iov.activity.BaseActivity;
import com.asiainfo.iov.activity.ScanActivity;
import com.framework.utils.ScreenUtils;
import com.yaxin.yyt.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class Fragment_homepage extends Fragment implements View.OnClickListener {
    private Context mContext;
    private View view;// infalte的布局
    private LinearLayout containerLayout;// 新建容器
    ////////////////////////////////
    private LinearLayout sellLayout, storeLayout;
    private ViewPager viewPager;
    private LinearLayout sellNumLayout, profitLayout, countLayout;
    private TextView tv_total, tv_profit, tv_sell_num;
    private boolean requestSuccess;

    /*Fragment开始*/
    private int oldposition = -1;
    private Fragment Center_mContent;
    private Fragment_linechart1 linechart1;
    private Fragment_linechart2 linechart2;
    private FrameLayout totalCountLayout, totalEarningLayout;
    private TextView tv_total_earning, tv_total_count;
    private ImageView iv_cursor;
    private Animation animation = null;
    private int[] arrPosition;
    private int position_zero, position_one;
    private int moveOldposition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            containerLayout = new LinearLayout(mContext);
            view = inflater.inflate(R.layout.fragment_homepage_percent, null);
            view.setMinimumHeight(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getHeight());
            view.setMinimumWidth(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getWidth());
            containerLayout.addView(view);
            EventBus.getDefault().register(this);
        } else {
            containerLayout.removeAllViews();
            containerLayout = new LinearLayout(getActivity());
            containerLayout.addView(view);
        }
        initView();
        initWidth();
        initFragment();
        initViewPager();
        requestSaleDetail();
//        ConstantRequestUtil.getInstance().requestJustShopIds((BaseActivity) mContext);

        return containerLayout;
    }

    //eventBus通知 getShopIdSuccess
    @Subscribe(threadMode = ThreadMode.MAIN, tag = " EventBusTag.getShopIdSuccess")
    public void getShopIdSuccess(String info) {
        requestSaleDetail();
    }

    //eventBus通知 getShopIdSuccess
    @Subscribe(threadMode = ThreadMode.MAIN, tag = "EventBusTag.shouldRefresh")
    public void shouldRefresh(String info) {
        requestSaleDetail();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void requestSaleDetail() {

    }

    private void initViewPager() {
//        ArrayList<GalleryInfo> list = new ArrayList<>();
//        for (int i = 0; i < 8; i++) {
//            GalleryInfo info = new GalleryInfo();
//            info.setAlreadySaleCount(i * 10);
//            info.setLastTotalSale(32 * i);
//            info.setStoreCount(6 * i);
//            info.setPhoneName("手机：" + i);
//            list.add(info);
//        }

//        GuidePagerAdapter adapter = new GuidePagerAdapter(mContext, list);
//        //40dp+(1-0.75)w/2=Margin  (MIN_SCALE=0.75,w=screenWidth-(20dpMargin+40dpMargin)*2)
//        viewPager.setPageTransformer(true, new CustomPageTransformer(ScreenUtils.getInstance().dip2px(mContext, 40)
//                + (1 - CustomPageTransformer.MIN_SCALE)
//                * (ScreenUtils.getInstance().getScreenWidthPx(mContext) - 2 * ScreenUtils.getInstance().dip2px
// (mContext, (40 + 20)))
//                / 2));
//        viewPager.setOffscreenPageLimit(2);
//        viewPager.setAdapter(adapter);
//        viewPager.setCurrentItem(Integer.MAX_VALUE / 2 - list.size());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sellLayout:
                ((BaseActivity) mContext).startActivity(ScanActivity.class);
                break;
            case R.id.storeLayout:
//                ((BaseActivity) mContext).startActivity(StoreActivity.class);
//                ((BaseActivity) mContext).startActivity(Store2Activity.class);
                break;
            case R.id.totalEarningLayout:
                showLeftFragment(true);
                initFragment();
                moveCursor(0, moveOldposition);
                break;
            case R.id.totalCountLayout:
                showLeftFragment(false);
                if (linechart2 == null)
                    linechart2 = new Fragment_linechart2();
                switchFragment(linechart2, 1);
                moveCursor(1, moveOldposition);
                break;
            case R.id.sellNumLayout:
                if (!requestSuccess) {
                    requestSaleDetail();
                }
                break;
            case R.id.profitLayout:
                if (!requestSuccess) {
                    requestSaleDetail();
                }
                break;
            case R.id.countLayout:
                if (!requestSuccess) {
                    requestSaleDetail();
                }
                break;
            default:
                break;
        }
    }

    private void initView() {
        sellLayout = (LinearLayout) view.findViewById(R.id.sellLayout);
        storeLayout = (LinearLayout) view.findViewById(R.id.storeLayout);

        tv_total = (TextView) view.findViewById(R.id.tv_total);
        tv_profit = (TextView) view.findViewById(R.id.tv_profit);
        tv_sell_num = (TextView) view.findViewById(R.id.tv_sell_num);

        sellNumLayout = (LinearLayout) view.findViewById(R.id.sellNumLayout);
        profitLayout = (LinearLayout) view.findViewById(R.id.profitLayout);
        countLayout = (LinearLayout) view.findViewById(R.id.countLayout);

        //3D轮播
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);

        totalCountLayout = (FrameLayout) view.findViewById(R.id.totalCountLayout);
        totalEarningLayout = (FrameLayout) view.findViewById(R.id.totalEarningLayout);
        tv_total_earning = (TextView) view.findViewById(R.id.tv_total_earning);
        tv_total_count = (TextView) view.findViewById(R.id.tv_total_count);
        iv_cursor = (ImageView) view.findViewById(R.id.cursor);

        totalCountLayout.setOnClickListener(this);
        totalEarningLayout.setOnClickListener(this);

        sellLayout.setOnClickListener(this);
        storeLayout.setOnClickListener(this);

        sellNumLayout.setOnClickListener(this);
        profitLayout.setOnClickListener(this);
        countLayout.setOnClickListener(this);
    }

    private void initFragment() {
        if (linechart1 == null) {
            linechart1 = new Fragment_linechart1();
        }
        switchFragment(linechart1, 0);
    }

    /**
     * @param isShowLeftFragment 是否显示左边fragment
     */
    private void showLeftFragment(boolean isShowLeftFragment) {
        tv_total_earning.setTextColor(getResources().getColor(isShowLeftFragment ? R.color._blue : R.color._gray_dark));
        tv_total_count.setTextColor(getResources().getColor(!isShowLeftFragment ? R.color._blue : R.color._gray_dark));
    }

    private void initWidth() {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        int screenW = ScreenUtils.getInstance().getScreenWidthPx(mContext);
        int initPosition = 0;
        int moveLenth = screenW / 2;
        position_zero = initPosition;
        position_one = moveLenth;
        arrPosition = new int[]{position_zero, position_one};
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                moveLenth, ScreenUtils.getInstance().dip2px(mContext, 3));
        iv_cursor.setLayoutParams(params);
    }

    public void moveCursor(final int position, int oldposition) {
        animation = new TranslateAnimation(arrPosition[oldposition],
                arrPosition[position], 0, 0);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        iv_cursor.startAnimation(animation);
        moveOldposition = position;
    }

    private void switchFragment(final Fragment fragment, final int position) {
        switchFragment(fragment, position, false);
    }

    private void switchFragment(final Fragment fragment, final int position, boolean mustReplace) {
        if (oldposition != position || mustReplace) {
            FragmentTransaction ft = getChildFragmentManager()
                    .beginTransaction();
            Fragment findresult = getChildFragmentManager().findFragmentByTag(
                    "viewid" + position);
            if (Center_mContent != null) {
                if (!mustReplace) {
                    ft.detach(Center_mContent);
                }
            }
            oldposition = position;
            if (findresult != null) {
                if (mustReplace) {
                    Center_mContent = fragment;
                    ft.replace(R.id.relative_center_homepage, Center_mContent, "viewid"
                            + position);
                } else {
                    ft.attach(findresult);
                    Center_mContent = findresult;
                }
            } else {
                Center_mContent = fragment;
                ft.add(R.id.centerLayout, Center_mContent, "viewid"
                        + position);
            }
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!requestSuccess) {
            requestSaleDetail();
        }
    }
}
